package com.lfy.websocket.handler;


import com.alibaba.dashscope.utils.JsonUtils;

import com.lfy.modules.common.domain.BaseChatMsg;
import com.lfy.websocket.cache.ChannelCache;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
/**
 * 业务处理类
 *
 * @author <a href="https://www.lvfeiy.top">lvfeiyang</a>
 * @date 2024/6/22 18:38
 */
@Slf4j
public class ChatHandler  extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接成功"+ctx.channel().id().asShortText());

    }
    /**
     * 断开连接
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.warn("触发 channelInactive 掉线![{}]", ctx.channel().id());
        ChannelCache.unBinding(ctx.channel());
    }
    /**
     * 出现异常时触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("ws: error :",cause);
        ctx.channel().close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame frame) throws Exception {
        String text = frame.text();
        log.info("收到消息：{}", text);
        // 解析消息
        BaseChatMsg message = JsonUtils.fromJson(text, BaseChatMsg.class);
        String type = message.getType();
        // 处理消息
        switch (type) {
            case "1":
                // 绑定用户
                ChannelCache.bind(message.getData(), channelHandlerContext.channel());

                break;
        }


    }
}
